package com.kayb.patterns.behavioral;

/**
 * 状态模式，允许内部状态变化时改变其行为
 * 场景：比如用户上下线、Java NIO
 * @author huangkaibin
 * @date 2018-08-29
 **/
public class State {

    enum StateEnum {
        FULL,
        EMPTY
    }

    interface IState {
        void press();
    }

    static class FullState implements IState {
        @Override
        public void press() {
            System.out.println("pouring water");
        }
    }

    static class EmptyState implements IState {
        @Override
        public void press() {
            System.out.println("no water");
        }
    }

    static class WaterDispenser {

        private int capacity = 20;
        private IState state;

        public WaterDispenser(IState state) {
            this.state = state;
        }

        private void setState(IState state) {
            this.state = state;
        }

        public IState getState() {
            return state;
        }

        public void press() {
            capacity--;
            if (capacity <= 0) {
                setState(new EmptyState());
            }
            state.press();
        }

    }

    public static void main(String[] args) {
        WaterDispenser dispenser = new WaterDispenser(new FullState());
        for (int i = 0; i < 25; ++i) {
            dispenser.press();
        }
    }

}
